package com.polidea.rxohosble2.sample.example5_rssi_periodic;


import com.polidea.rxohosble2.RxBleConnection;
import com.polidea.rxohosble2.RxBleDevice;
import com.polidea.rxohosble2.sample.DeviceAbility;
import com.polidea.rxohosble2.sample.SampleApplication;
import com.polidea.rxohosble2.sample.ResourceTable;
import io.reactivex.ohos.schedulers.OhosSchedulers;
import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;

import static java.util.concurrent.TimeUnit.SECONDS;

public class RssiPeriodicExampleAbility extends Ability {


    Text connectionStateView;

    Text rssiView;

    Button connectButton;
    private RxBleDevice bleDevice;
    private Disposable connectionDisposable;
    private Disposable stateDisposable;


    public void onConnectToggleClick() {

        if (isConnected()) {
            triggerDisconnect();
        } else {
            connectionDisposable = bleDevice.establishConnection(false)
                    .doFinally(this::clearSubscription)
                    .flatMap(rxBleConnection -> // Set desired interval.
                            Observable.interval(2, SECONDS).flatMapSingle(sequence -> rxBleConnection.readRssi()))
                    .observeOn(OhosSchedulers.mainThread())
                    .subscribe(this::updateRssi, this::onConnectionFailure);
        }
    }

    private void updateRssi(int rssiValue) {
        rssiView.setText(getString(ResourceTable.String_read_rssi, rssiValue));
    }

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        setUIContent(ResourceTable.Layout_ability_example5);
        String macAddress = getIntent().getStringParam(DeviceAbility.EXTRA_MAC_ADDRESS);
//        setTitle(getString(ResourceTable.String_mac_address, macAddress));//用Text代替
        bleDevice = SampleApplication.getRxBleClient(this).getBleDevice(macAddress);

        // How to listen for connection state changes
        stateDisposable = bleDevice.observeConnectionStateChanges()
                .observeOn(OhosSchedulers.mainThread())
                .subscribe(this::onConnectionStateChange);
    }


    private boolean isConnected() {
        return bleDevice.getConnectionState() == RxBleConnection.RxBleConnectionState.CONNECTED;
    }

    private void onConnectionFailure(Throwable throwable) {
        //noinspection ConstantConditions
        new ToastDialog(getContext()).setText("Connection error:"+throwable).setDuration(3000).show();
    }

    private void onConnectionStateChange(RxBleConnection.RxBleConnectionState newState) {
        connectionStateView.setText(newState.toString());
        updateUI();
    }

    private void clearSubscription() {
        connectionDisposable = null;
        updateUI();
    }

    private void triggerDisconnect() {

        if (connectionDisposable != null) {
            connectionDisposable.dispose();
        }
    }

    private void updateUI() {
        final boolean connected = isConnected();
        connectButton.setText(connected ? ResourceTable.String_disconnect : ResourceTable.String_connect);
    }


    @Override
    protected void onInactive() {
        super.onInactive();
        triggerDisconnect();
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (stateDisposable != null) {
            stateDisposable.dispose();
        }
    }

}
